/**
 *  JSimProd - Java simulation code for production processes
 *  Copyleft Jorge Mira Yagüe <jorge.mira.yague@gmail.com>
 *  Universidad de Alicante 2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package lib.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import lib.exceptions.InvalidBatchsValueException;
import lib.exceptions.InvalidLengthException;
import lib.exceptions.OverlappedIntervalException;
import lib.exceptions.UnfulfillableRestrictionsException;
import lib.exceptions.XMLParsingException;
import lib.model.*;
import lib.model.distribution.*;
import lib.model.queue.QueueType;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 * This class is used to load a factory model from a XML file
 * @author Jorge Mira Yagüe
 */
public class FactoryModelReader extends DefaultHandler {

    private final XMLReader xr;
    private FactoryModel factoryModel;
    private Station station;
    private ItemCategory category;
    private Task task;
    private Distribution dist;
    private Interval interval;
    private String taskName;
    private String connexionName;
    private String stationName;
    private Restriction restriction;
    private List<Interval> intervals;
    private List<Restriction> restrictions;
    private boolean error;

    /**
     * Class builder
     * @throws SAXException
     */

    public FactoryModelReader() throws SAXException {
        xr = XMLReaderFactory.createXMLReader();
        xr.setContentHandler(this);
        xr.setErrorHandler(this);
    }

    /**
     * This function builts a factory model from a given XML file
     * @param xmlFile The file to build the factory model from
     * @return The factory model from the given file
     * @throws FileNotFoundException
     * @throws IOException
     * @throws SAXException
     * @throws XMLParsingException
     */
    public FactoryModel getFMFromXML(File xmlFile)
            throws FileNotFoundException,
            IOException,
            SAXException,
            XMLParsingException {
        FileReader fr = new FileReader(xmlFile);
        error = false;
        xr.parse(new InputSource(fr));
        if (error) {
            throw new XMLParsingException(xmlFile.getName());
        }
        return factoryModel;
    }

    @Override
    public void startElement(String uri,
            String name,
            String qName,
            Attributes atts) {

        if (name.equals("FactoryModel")) {
            Calendar calendar;
            factoryModel = new FactoryModel(atts.getValue("name"));
            calendar = Calendar.getInstance();
            calendar.setTimeInMillis(Long.parseLong(
                    atts.getValue("whenModified")));
            factoryModel.setWhenModified(calendar);
        } else if (name.equals("ItemCategory")) {
            category = new ItemCategory(atts.getValue("name"),
                    atts.getValue("description"),
                    ICColor.valueOf(atts.getValue("color")));
        } else if (name.equals("Task")) {
            task = new Task(atts.getValue("name"),
                    null,
                    atts.getValue("description"),
                    Boolean.parseBoolean(atts.getValue("sameShift")));
        } else if (name.equals("Distribution")) {
            double mean = Double.parseDouble(atts.getValue("mean"));
            double variance = Double.parseDouble(atts.getValue("variance"));
            switch (DistributionType.valueOf(atts.getValue("type"))) {
                case EXPONENTIAL:
                    dist = new ExponentialDistribution(mean, variance);
                    break;
                case NORMAL:
                    dist = new NormalDistribution(mean, variance);
                    break;
                case STATIC:
                    dist = new StaticDistribution(mean);
                    break;
                case UNIFORM:
                    dist = new UniformDistribution(mean, variance);
                    break;
            }
        } else if (name.equals("BufferedStation")) {
            try {
                station = new BufferedStation(atts.getValue("name"),
                        QueueType.valueOf(atts.getValue("queueType")),
                        Integer.parseInt(atts.getValue("minBatch")),
                        Integer.parseInt(atts.getValue("maxBatch")));
            } catch (InvalidBatchsValueException ibve) {
                error = true;
            }
        } else if (name.equals("Station")) {
            station = new Station(atts.getValue("name"),
                    QueueType.valueOf(atts.getValue("queueType")));
        } else if (name.equals("StationCalendar")) {
            intervals = new ArrayList<Interval>();
        } else if (name.equals("Interval")) {
            Calendar c1, c2;
            c1 = Calendar.getInstance();
            c1.setTimeInMillis(Long.parseLong(
                    atts.getValue("start")));
            c2 = Calendar.getInstance();
            c2.setTimeInMillis(Long.parseLong(
                    atts.getValue("end")));
            try {
                interval = new Interval(c1, c2);
            } catch (InvalidLengthException ile) {
                error = true;
            }
        } else if (name.equals("taskName")) {
            taskName = atts.getValue("name");
        } else if (name.equals("connexionName")) {
            connexionName = atts.getValue("name");
        } else if (name.equals("stationName")) {
            stationName = atts.getValue("name");
        } else if (name.equals("restrictions")) {
            restrictions = new ArrayList<Restriction>();
        } else if (name.equals("Restriction")) {
            try {
                restriction = new Restriction(atts.getValue("itemCategoryName"),
                        Integer.parseInt(atts.getValue("minBatch")),
                        Integer.parseInt(atts.getValue("maxBatch")));
            } catch (InvalidBatchsValueException ibve) {
                error = false;
            }
        }
    }

    @Override
    public void endElement(String uri, String name, String qName) {
        if (name.equals("ItemCategory")) {
            factoryModel.addItemCategory(category);
        } else if (name.equals("Task")) {
            category.addTask(task);
        } else if (name.equals("Distribution")) {
            task.setDistribution(dist);
        } else if (name.equals("BufferedStation")) {
            factoryModel.addStation(station);
        } else if (name.equals("Station")) {
            factoryModel.addStation(station);
        } else if (name.equals("repairs")) {
            try {
                station.addRepairs(intervals);
            } catch (OverlappedIntervalException oie) {
                error = true;
            }
        } else if (name.equals("shifts")) {
            try {
                station.addShifts(intervals);
            } catch (OverlappedIntervalException oie) {
                error = true;
            }
        } else if (name.equals("Interval")) {
            intervals.add(interval);
        } else if (name.equals("taskName")) {
            station.addTask(taskName);
        } else if (name.equals("connexionName")) {
            station.addConnexion(connexionName);
        } else if (name.equals("stationName")) {
            task.addStation(stationName);
        } else if (name.equals("restrictions")) {
            try {
                ((BufferedStation) station).setRestrictions(restrictions);
            } catch (UnfulfillableRestrictionsException ure) {
                error = true;
            }
        } else if (name.equals("Restriction")) {
            restrictions.add(restriction);
        }
    }
}
